package com.wyx.Controller;

import com.wyx.Common.Code;
import com.wyx.Common.Result;
import com.wyx.Pojo.User;
import com.wyx.Service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
/**
 * 图书的视图层
 */
@RestController
@RequestMapping("/users")
public class userController {
    @Autowired
    private UserService userService;

    /**
     * 用户的登录校验
     * @param user
     * @param req
     * @param res
     * @return
     */

    @PostMapping
    public Result user(@RequestBody User user, HttpServletRequest req, HttpServletResponse res){
        Integer code;
        String msg;
        if (userService.selectUser(user)!=null){
            code= Code.USER_OK;
            req.getSession().setAttribute("user",user.getUsername());
            msg="";
            return new Result(userService.selectUser(user),code,msg);
        }else {
            code=Code.USER_ERR;
            msg="用户不存在，请重新输入";
            return new Result(userService.selectUser(user),code,msg);
        }
    }

    /**
     * 查询用户名是否被注册
     * @param username
     * @return
     */
    @GetMapping("/{username}")
    public Result username(@PathVariable String username){
//        System.out.println(username);
        Integer code;
        String msg;
        if (userService.selectUserByusername(username)){
            code=Code.USERNAME_OK;
            msg="";
        }else {
            code=Code.USERNAME_ERR;
            msg="用户已存在，请重新输入";
        }
//        System.out.println(code);
//        System.out.println(userService.selectUserByusername(username));
        return new Result(null,code,msg);
    }

    /**
     * 注册用户
     * @param user
     * @return
     */
    @PostMapping("/1")
    public Result saveuser(@RequestBody User user){
        System.out.println(user);
        Integer code;
        String msg;
        if (userService.saveUser(user)){
            code=Code.SAVEUSER_OK;
            msg="";
        }else {
            code=Code.SAVEUSER_ERR;
            msg="系统繁忙，请稍后再试";
        }
        return new Result(null,code,msg);
    }
}
